/*
 * Logger.java
 *
 * Created on 30 January 2005, 18:35
 */

package org.foment.joliage3.core.logging;

import java.io.IOException;
import java.io.PrintStream;
import java.util.Date;
import java.util.Vector;
/**
 *
 * @author civan
 */
public class Logger {
  public interface LoggerEventListener {
    public void logEvent(String progID, String file, int type, String message, Exception exception);
  }
  
  
  private static Vector<LoggerEventListener> listeners = new Vector();
  
  public static void addLogListener(LoggerEventListener listener) {
    listeners.add(listener);
  }
  
  public static void removeLogListener(LoggerEventListener listener) {
    listeners.remove(listener);
  }
  
  public static final int UNKNOWN       = -1;
  public static final int FATAL_ERROR   =  1;
  public static final int ERROR         =  2;
  public static final int WARNING       =  4;
  public static final int MESSAGE       =  8;
  public static final int DEBUG         = 16;
  
  private static boolean _initialized = false;
 
  private static java.io.PrintStream logFile = null;
  
  public static void init() {
    String logPath = org.foment.joliage3.core.system.Paths.getApplicationHomePath("/log/");
    (new java.io.File(logPath)).mkdirs();
    
    try {
      String logDate = (new java.text.SimpleDateFormat("yyyy-MM-dd")).format(new java.util.Date());
      logFile = new java.io.PrintStream(new java.io.FileOutputStream(logPath + "program.log." + logDate, true));
    } catch (IOException ex) {
      logFile = System.err;
      ex.printStackTrace(logFile);
    }
    
    _initialized = true;
  }
  
  public static void log(String progID, String file, int type, String message, Exception exception) {
    if (!_initialized) init();
    
    logFile.println(new java.util.Date());
    logFile.println("Program '" + progID + "' in '" + file + "' logged the following message of type [" + String.valueOf(type) + "]:\n" + message);
    if (exception != null) {
      logFile.println("Exception data:");
      logFile.println(exception.getMessage());
      exception.printStackTrace(logFile);
      logFile.flush();
    }
    logFile.println("------------------------------------------------------------\n\n");
    
    for (LoggerEventListener listener : listeners) {
      listener.logEvent(progID, file, type, message, exception);
    }
  }
}
